package com.boda.web.service.template;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.boda.common.util.ObjUtil;
import com.boda.common.util.str.StringUtil;
import com.boda.web.model.PageModel;
import com.boda.web.model.template.TestModel;
import com.boda.web.service.BaseService;

@Service
public class TestService extends BaseService {

    public PageModel getListByPage(TestModel test, int offset, int pageSize) {
        StringBuffer sbSql = new StringBuffer("select id, NAME, age from test where 1=1");
        StringBuffer sbSqlCount = new StringBuffer("select count(*) from test where 1=1");
        StringBuffer sbSqlWhere = new StringBuffer();

        List<Object> lstParam = new ArrayList<Object>();
        if (StringUtil.isNotEmpty(test.getName())) {
            sbSqlWhere.append(" and name like ?");
            lstParam.add("%" + test.getName() + "%");
        }
        if (test.getAge() != null) {
            sbSqlWhere.append(" and age = ?");
            lstParam.add(test.getAge());
        }

        sbSql.append(sbSqlWhere);
        sbSqlCount.append(sbSqlWhere);
        sbSql.append(" order by id ");

        List<Map<String, Object>> lst = db.queryForPage(sbSql.toString(), lstParam.toArray(), offset, pageSize);
        int count = db.queryForInt(sbSqlCount.toString(), lstParam.toArray());

        PageModel page = new PageModel();
        page.setData(lst);
        page.setTotal(count);
        return page;
    }

    public TestModel getTest(String id) {
        String sql = "select id, NAME, age from test where id=?";
        List<Map<String, Object>> lst = db.queryForList(sql, new Object[] { Integer.valueOf(id) });
        TestModel test = new TestModel();
        if (lst != null && !lst.isEmpty()) {
            Map<String, Object> map = lst.get(0);
            test.setId(ObjUtil.toInt(map.get("id")));
            test.setAge(ObjUtil.toInt(map.get("age")));
            test.setName((String) map.get("name"));
        }
        return test;
    }

    public boolean add(TestModel test) {
        String sql = "insert into test(name,age) values (?,?)";
        db.update(sql, new Object[] { test.getName(), test.getAge() });
        return true;
    }

    public boolean edit(TestModel test) {
        boolean result = false;
        String sql = "update test set name=?,age=? where id=?";
        db.update(sql, new Object[] { test.getName(), test.getAge(), test.getId() });
        return result;
    }

    public boolean delete(String id) {
        boolean result = false;
        String sql = "delete from test where id=?";
        db.update(sql, new Object[] { Integer.valueOf(id) });
        return result;
    }

}
